package com.chezhujie.www.controller.api;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.chezhujie.www.core.quartz.AppMap;
import com.chezhujie.www.domain.Czjdeliveryadd;
import com.chezhujie.www.domain.Czjexpress;
import com.chezhujie.www.domain.CzjexpressPic;
import com.chezhujie.www.domain.Czjorder;
import com.chezhujie.www.domain.Czjuserinfo;
import com.chezhujie.www.domain.Czjusermess;
import com.chezhujie.www.domain.IP;
import com.chezhujie.www.domain.vo.CzjuserAll;
import com.chezhujie.www.enums.Expresstatus;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.service.ApitwjService;
import com.chezhujie.www.service.CzjdeliveryaddService;
import com.chezhujie.www.service.CzjexpressPicService;
import com.chezhujie.www.service.CzjexpressService;
import com.chezhujie.www.service.CzjmemberService;
import com.chezhujie.www.service.CzjorderService;
import com.chezhujie.www.service.CzjuserinfoService;
import com.chezhujie.www.service.CzjusermessService;
import com.chezhujie.www.service.IPService;
import com.sys.core.utils.CusAccessObjectUtil;
import com.sys.core.utils.ImgBase64Util;
import com.sys.core.utils.SendCodeUtils;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;

@Controller
@RequestMapping("/api/")
public class CzjuserinfoController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(CzjuserinfoController.class);

	// 登陆
	@RequestMapping("login.do")
	public void login(@RequestParam(required = true) String telephone,
			@RequestParam(required = true) String password,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {

			Czjuserinfo czjuserinfo = czjuserinfoService
					.loginUserInfo(telephone.trim());
			if (null != czjuserinfo && !"".equals(czjuserinfo)) {
				Map<String, Object> result = new HashMap<String, Object>();
				String pwd = czjuserinfo.getPassword();
				if (StringUtils.isNotBlank(pwd)) {

					if (pwd.equals(password.trim())) {
						
					if(czjuserinfo.getEnable().equals("N")){
						jsonResult(0, "162", "用户已被锁定", result, response);		
						return ;
						}

						result.put("userId", czjuserinfo.getId());
						result.put("nickname", czjuserinfo.getNickname());
						result.put("phone", czjuserinfo.getTelephone());
						
						
						jsonResult(1, "103", "登陆成功", result, response);
						return;
					} else {
						jsonResult(0, "104", "密码错误", result, response);
						return;
					}
				} else {
					jsonResult(0, "105", "用户密码为空", result, response);
					return;
				}

			} else {
				jsonResult(0, "102", "手机号码不存在，尚未注册", "", response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("101", e);
			jsonResult(0, "101", "登陆异常", "", response);

		}

	}

	// 注册
	@RequestMapping("register.do")
	public void register(Czjuserinfo czjuserinfo,
			@RequestParam(required = true) String code,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();

		if (StringUtils.isBlank(czjuserinfo.getTelephone())) {
			jsonResult(0, "106", "手机号码不能为空", "", response);
			return;
		}
		if (StringUtils.isBlank(czjuserinfo.getPassword())) {
			jsonResult(0, "105", "用户密码为空", result, response);
			return;
		}
		try {

			// 判断手机号码是否已经注册
			Czjuserinfo cinfo = czjuserinfoService.loginUserInfo(czjuserinfo
					.getTelephone());
			if (null != cinfo) {
				jsonResult(0, "108", "手机号码已经注册", result, response);
				return;
			}

			// 校验短信验证的时效 和 对错
			if (AppMap.getVcode(czjuserinfo.getTelephone()) == null) {
				jsonResult(0, "110", "验证码失效", result, response);
				return;
			}
			if (!request.getParameter("code").equals(
					AppMap.getVcode(czjuserinfo.getTelephone()))) {
				jsonResult(0, "110", "验证码不正确", result, response);
				return;
			}
			//验证码移除缓存
			AppMap.removeVcode(czjuserinfo.getTelephone());
			//
			czjuserinfo.setType(0); // 用户类型
			czjuserinfo.setCreatetime(new Date());
			czjuserinfo.setEnable("Y");
			czjuserinfo.setIsdelete("0");
			czjuserinfo.setIdentity("0");
			czjuserinfoService.insertCzjuserinfoByAuto(czjuserinfo);
			int lastInsertId = czjuserinfoService.findlastInsert();
			result.put("userId", lastInsertId);

			jsonResult(1, "108", "注册成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("注册用户异常", e);
			jsonResult(0, "107", "系统异常", "", response);

		}

	}
	

	/**
	 *
	 * 方法名：sendMSM 创建人：RUI 时间：2017年5月2日-上午9:31:58
	 * 
	 * @param pid
	 * @param telephone
	 * @param type
	 *            1注册验证码 2忘记密码验证码
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping(value="sendMSM.do",method=RequestMethod.POST)
	public void sendMSM(@RequestParam(required = true) String telephone,
			@RequestParam(required = true) Integer type,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			
			String ipAddress=CusAccessObjectUtil.getIpAddress(request);
			if(StringUtils.isNotBlank(ipAddress)){
			Map<String, Object> params=new HashMap<>();
			params.put("address", ipAddress);
			params.put("createtime", new Date());
			int count=ipService.selectCountByIp(params);
			//  数据库查询还要根据时间查询   以及IP判断校验也没有做
			if(count>=10){
				jsonResult(0, "176", "验证码超出今日所发上限", "", response);
				return ;
			}
			//记录短信IP
			IP ip=new IP();
			ip.setAddress(ipAddress);
			ip.setCreatetime(new Date());
			ip.setIpId(UUIDUtils.getUUID());
			ipService.insert(ip);
			//
			}
			
			Map<String, Object> map=new HashMap<String, Object>();
				map.put("telephone", telephone);
			int i=czjuserinfoService.findPhone(map);
			if(type==1){
				if(i>0){
					jsonResult(0, "141", "该手机号码已经注册,短信发送失败", "", response);
					return ;
				}	
			}
			if(type==2){
				if(i<=0){
					jsonResult(0, "142", "系统没有该手机号码，短信发送失败", "", response);
					return ;
				}
			}

			// 发送短信
			Map<String, Object> strJson=SendCodeUtils.sendCode(telephone,type);
			Double code=(Double) strJson.get("code");
			if(code==200.0){//短信发送成功
				String obj=(String) strJson.get("obj");//短信验证码
				AppMap.setVcode(obj, telephone);
				jsonResult(1, "109", "短信发送成功", "", response);
				return ;
			}else{
				
				if(code==416.0){//频率控制
					jsonResult(0, "176", "验证码超出今日所发上限", "", response);
					return ;
				}else{
					jsonResult(0, "184", "发送给短信回执错误", "", response);
					return ;
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取验证码出错", e);
			jsonResult(0, "110", "短信发送失败", "", response);
		}

	}

	/**
	 * 忘记密码 方法名：forgotPwd 创建人：RUI 时间：2017年5月2日08:55:57
	 * 
	 * @param czjusermess
	 * @param file
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("forgotPwd.do")
	public void forgotPwd(@RequestParam(required = true) String phone,
			@RequestParam(required = true) String password,
			@RequestParam(required = true) String code,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();

		try {

			// 校验短信验证的时效 和 对错
			if (AppMap.getVcode(phone) == null) {
				jsonResult(0, "110", "验证码失效", result, response);
				return;
			}
			if (!request.getParameter("code").equals(
					AppMap.getVcode(phone))) {
				jsonResult(0, "110", "验证码不正确", result, response);
				return;
			}
			//验证码移除缓存
			AppMap.removeVcode(phone);
			// 修改密码
			Czjuserinfo czjuserinfo = new Czjuserinfo();
			czjuserinfo.setPassword(password);
			czjuserinfo.setTelephone(phone);
			czjuserinfoService.updatePwdByPhone(czjuserinfo);
			jsonResult(1, "121", "修改密码成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("修改密码异常", e);
			jsonResult(0, "107", "系统异常", "", response);
		}

	}

	

	/**
	 * 
	 * 方法名：findUserAll 查询用户基本信息和收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("findUserAll")
	public void findUserAll(@RequestParam(required = true) Integer id,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			CzjuserAll czjuserAll = czjuserinfoService.findUserAll(map);
			jsonResult(1, "", "", czjuserAll, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("127", e);
			jsonResult(0, "127", "查询用户基本信息失败", "", response);
		}

	}

	/**
	 * 
	 * 方法名：updateUser 修改用户基本信息 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("updateUser")
	public void updateUserById(@RequestParam(required = true) Integer id,
			HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = false) String picPath, ModelMap model)
			throws Exception {

		try {
			String nickname = request.getParameter("nickname");
			String usermessId = request.getParameter("usermessId");
			String sex = request.getParameter("sex");
			String reginon = request.getParameter("reginon");
			String deliveryaddId = request.getParameter("deliveryaddId");
			String address = request.getParameter("address");

			//个人表 begin
			Czjuserinfo czjuserinfo = new Czjuserinfo();
			czjuserinfo.setId(id);
			czjuserinfo.setNickname(nickname);
			czjuserinfoService.updateCzjuserinfo(czjuserinfo);
			//end
			
			//收货地址 begin
			Czjdeliveryadd czjdeliveryadd = new Czjdeliveryadd();
			czjdeliveryadd.setDeliveryaddId(deliveryaddId);
			czjdeliveryadd.setAddress(address);
			if (StringUtils.isNotBlank(deliveryaddId)) {

				czjdeliveryaddService.updateDelivery(czjdeliveryadd);
			}
			
			//end
			
			//用户关联基本信息
			Czjusermess czjusermess = czjusermessService.queryByUserinfoId(id);
			if(null==czjusermess){
				czjusermess=new Czjusermess();
				if(null !=sex){
					czjusermess.setSex(Integer.valueOf(sex));
				}
				czjusermess.setUserinfoId(id);
				czjusermess.setReginon(reginon);
				czjusermess.setNoComment("N");//默认可评论
				if (picPath!=null && picPath.length() > 0) {

					String pathRoot = request.getSession().getServletContext()
							.getRealPath("");
					String picName = UUIDUtils.getDateUUID();
					String path = "/upload/" + picName+"-"+System.currentTimeMillis() + ".jpg";// 数据库保存路径
					boolean isTrue = ImgBase64Util.generateImage(picPath, pathRoot
							+ path);
					if (isTrue == false) {
						jsonResult(0, "120", "转存头像失败", "", response);
						return;
					}

					czjusermess.setPicPath(path);
//					String mediumPic = genernateMediumPic("/upload/comments/pic/",basePath,listPicfile.get(i).getPicPath(),listPicfile.get(i).getCommentsId());
					String mediumPic = apitwjService.genernateMediumPic("/upload/comments/pic/",request,path,czjusermess.getUsermessId());
					czjusermess.setPicPath(mediumPic);
				}
				czjusermessService.insertUsermess(czjusermess);
			}else{
				if(null !=sex){
					czjusermess.setSex(Integer.valueOf(sex));
				}
				if(null==czjusermess.getNoComment()){
					czjusermess.setNoComment("N");//默认可评论
				}
				czjusermess.setUserinfoId(id);
				czjusermess.setReginon(reginon);
				if (picPath!=null && picPath.length() > 0) {

					String pathRoot = request.getSession().getServletContext()
							.getRealPath("");
					String picName = UUIDUtils.getDateUUID();
					String path = "/upload/" + picName+"-"+System.currentTimeMillis() + ".jpg";// 数据库保存路径
					boolean isTrue = ImgBase64Util.generateImage(picPath, pathRoot
							+ path);
					if (isTrue == false) {
						jsonResult(0, "120", "转存头像失败", "", response);
						return;
					}

					czjusermess.setPicPath(path);
//					String mediumPic = genernateMediumPic("/upload/comments/pic/",basePath,listPicfile.get(i).getPicPath(),listPicfile.get(i).getCommentsId());
					String mediumPic = apitwjService.genernateMediumPic("/upload/comments/pic/",request,path,czjusermess.getUsermessId());
					czjusermess.setPicPath(mediumPic);

				}
				
				czjusermessService.updateUsermess(czjusermess);
			}
			
		
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", id);
			jsonResult(1, "", "", map, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("128", e);
			jsonResult(0, "128", "修改用户信息失败", "", response);
		}

	}

	/**
	 * 
	 * 方法名：findDeliveryById 查询用户收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("findDeliveryById.do")
	public void findDeliveryById(@RequestParam(required = true) String id,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			if(StringUtils.isBlank(id)){
				jsonResult(0, "178", "用户为空", "", response);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userinfoId", id);
			map.put("del", 1); 
			List<Czjdeliveryadd> czjdeliveryadds = czjdeliveryaddService
					.findDeliById(map); // 根据用户id查询收货地址
			jsonResult(1, "", "", czjdeliveryadds, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("129", e);
			jsonResult(0, "129", "查询用户收货地址错误", "", response);
		}
	}

	/**
	 * 
	 * 方法名：insertDelivery 新增用户收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("insertDelivery.do")
	public void insertDelivery(@RequestParam(required = true) Integer id,
			Czjdeliveryadd czjdeliveryadd, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws Exception {

		try {
			czjdeliveryadd.setUserinfoId(id);
			czjdeliveryadd.setCreatetime(new Date());
			czjdeliveryadd.setDel(1);
			
			if(null==czjdeliveryadd.getDef())
				czjdeliveryadd.setDef(0);
			czjdeliveryaddService.insertDelivery(czjdeliveryadd);
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("130", e);
			jsonResult(0, "130", "新增用户收货地址错误", "", response);
		}

	}

	/**
	 * 
	 * 方法名：updateDeliveryDef 设置用户默认收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("updateDeliveryDef")
	public void updateDeliveryDef(@RequestParam(required = true) Integer id,
			@RequestParam(required = true) String deliveryaddId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			// 默认地址只能有一个，首先把这个用户的其它收货地址设置为0
			Czjdeliveryadd czjdeliveryadd = new Czjdeliveryadd();
			czjdeliveryadd.setUserinfoId(id);
			czjdeliveryadd.setDef(0);
			czjdeliveryaddService.updateDeliveryDef(czjdeliveryadd);
			czjdeliveryadd.setDeliveryaddId(deliveryaddId);
			czjdeliveryadd.setDef(1);
			czjdeliveryaddService.updateDelivery(czjdeliveryadd);
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("131", e);
			jsonResult(0, "131", "设置用户默认收货地址错误", "", response);
		}
	}

	
	public boolean volidateVodeType(String type) {
		if (type.equalsIgnoreCase("mp4") || type.equalsIgnoreCase("avi")
				|| type.equalsIgnoreCase("rmvb")
				|| type.equalsIgnoreCase("quicktime"))
			return true;
		else
			return false;
	}
	
	

	/**
	 * 
	 * 方法名：svseExpress 用户输入回去的快递 信息
	 * 创建人：RUI
	 * 时间：2017年8月21日-下午7:39:11 
	 * @param czjexpress
	 * @param req
	 * @param resp
	 * @param httpSession
	 * @param model
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("svseReturnExpress")
	public void svseReturnExpress(Czjexpress czjexpress,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession httpSession, ModelMap model) {

		try {
			if(czjexpress.getStatus()!=OrderStatus.FINENDLEASE.getIndex()){//
				
				jsonResult(0, "190", "归还非法请求", "", resp);
				return ;
			}
			if(null==czjexpress.getExpressId() || "".equals(czjexpress.getExpressId())){
				
				czjexpress.setStatus(Expresstatus.RETURN.getIndex());
				czjexpressService.insertCzjexpress(czjexpress);
				//  修改订单状态为
				Map<String, Object> map=new HashMap<>();
					map.put("orderCode", czjexpress.getOrderCode());
				Czjorder czjorder=czjorderService.getOneBy(map);
					czjorder.setStatus(OrderStatus.STAYBACK.getIndex());
				czjorderService.update(czjorder);
				//
		
			}else{
				czjexpressService.updateCzjexpress(czjexpress);
			}
				
			jsonResult(1, "", "", "", resp);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "185", "户输入回去的快递信息错误", "", resp);
			
		}

	}
	
	/**
	 * 
	 * 方法名：returnExpress 上传产品图片（回寄产品）
	 * 创建人：RUI
	 * 时间：2017年8月21日-下午7:40:30 
	 * @param multipartFiles
	 * @param czjexpress
	 * @param req
	 * @param resp
	 * @param model void
	 * @exception 
	 * @since  1.0.0
	 */
    @RequestMapping("/svseReturnExpressPic")
    public void svseReturnExpressPic (@RequestParam(value = "picPath", required = false) MultipartFile []multipartFiles,
            Czjexpress czjexpress, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

        	//新增图片
        	String pathRoot = req.getSession().getServletContext().getRealPath("");
			File fileDir = new File(pathRoot + "/upload");
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			
			CzjexpressPic czjexpressPic=null;
			for(int i=0;i<multipartFiles.length;i++){
				String filePath = "/upload/" + UUIDUtils.getUUID();
				String contentType =
						  multipartFiles[i].getContentType(); // 获得文件后缀名称 
				String imageName =
						 contentType.substring(contentType .indexOf("/") + 1); 
				
				if(multipartFiles[i].getSize()>0){
					czjexpressPic=new CzjexpressPic();
					multipartFiles[i].transferTo(new File(pathRoot + filePath+"."+imageName));
					czjexpressPic.setPicPath(filePath+"."+imageName);
					czjexpressPic.setExpressPicId(UUIDUtils.getUUID());
					czjexpressPic.setCreateTime(new Date());
					czjexpressPicService.insert(czjexpressPic);
				}
				
			}
			jsonResult(1, "", "", "", resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0, "186", "上传产品图片（回寄产品）错误", "", resp);
        }
        
    }

	@Resource
	private CzjuserinfoService czjuserinfoService;

	@Resource
	private CzjmemberService czjmemberService;

	@Resource
	private CzjdeliveryaddService czjdeliveryaddService;

	@Resource
	private CzjusermessService czjusermessService;
	
	@Resource
	private ApitwjService apitwjService;
	
	@Resource
	private IPService ipService;
	
	@Autowired
	private CzjexpressService czjexpressService;
	
	@Autowired
	private CzjexpressPicService czjexpressPicService;
	
	@Autowired
	private CzjorderService czjorderService;

}